<template>
  <el-drawer
    v-model="dialogFormVisible"
    :title="title"
    direction="rtl"
    size="65%"
    :with-header="false"
    @close="close"
  >
    <customer ref="customerRef" :customer="customer" />
  </el-drawer>
</template>

<script>
  import { doEdit, getJobInfo } from '@/api/boyiJob'
  import Customer from '@/views/boyi/customer/components/Customer'

  export default defineComponent({
    name: 'CustomerDrawer',
    components: { Customer },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        formRef: null,
        customerRef: null,
        form: {
          roles: [],
        },
        rules: {
          title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
        },
        title: '',
        activeName: '1',
        job: {},
        customer: {
          job_list: [],
        },
        reRequest: {},
        dialogFormVisible: false,
      })

      const showEdit = (customer) => {
        state.customer = Object.assign({}, customer)
        state.dialogFormVisible = true
      }
      const close = () => {
        // state['formRef'].resetFields()
        state.form = {
          roles: [],
        }
        state.dialogFormVisible = false
      }
      const handleJob = () => {
        emit('fetch-data')
        state.dialogFormVisible = false
      }

      // 获取job信息
      const getJobInfoData = async (job) => {
        const { data } = await getJobInfo({ job_id: job.id })
        // state.job = Object.assign({}, data)
        console.log(data)

        state.customer.job_list.forEach((item, index) => {
          if (item.id === job.id) {
            state.customer.job_list[index] = Object.assign({}, data)
          }
        })
      }

      const handleTabChange = (index) => {
        console.log(index)
        if (!state.reRequest[index]) {
          getJobInfoData(state.customer.job_list[index])
          state.reRequest[index] = true
        }
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doEdit(state.form)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
        handleJob,
        handleTabChange,
        getJobInfoData,
      }
    },
  })
</script>
